package com.courage.crawler.boss.service.crawler;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class SelectRegionCrawlerRule implements CrawlerRule {

    private boolean firstTime = true;

    @Override
    public void doAction(ChromeDriverContext chromeDriverContext) throws InterruptedException {
        log.info("选择区域爬虫规则");
        ChromeDriver chromeDriver = chromeDriverContext.getChromeDriver();
        List<WebElement> list = chromeDriver.findElements(new By.ByCssSelector(".dropdown-city-list li"));
        boolean hit = false;

        int cursor = 0;
        WebElement activeRegion = null;
        for (int i = 0; i < list.size(); i++) {
            WebElement webElement = list.get(i);
            String className = webElement.getAttribute("class");
            if ("active".equals(className)) {
                hit = true;
                cursor = i;
                activeRegion = webElement;
                break;
            }
        }
        if (!hit || firstTime) {
            WebElement webElement = list.get(0);
            log.info("没有选择区域，默认选择第一个选项 ，区域名：" + webElement.getText());
            webElement.click();
            Thread.sleep(11000);
            firstTime = false;
        } else {
            log.info("已选择区域，区域名：" + activeRegion.getText() + " isPageEnd:" + chromeDriverContext.isPageEnd());
            if (list.size() > cursor + 1 && chromeDriverContext.isPageEnd()) {
                WebElement nextLink = list.get(cursor + 1);
                nextLink.click();
                chromeDriverContext.setPageEnd(false);
                Thread.sleep(4892);
            } else {
                log.info("处理分页请求：" + chromeDriver.getCurrentUrl());
            }
        }
    }

}
